<template>
  <div class="points-page">
    <div class="page-header">
      <h2 class="page-title">积分中心</h2>
    </div>

    <!-- 积分概览卡片 -->
    <div class="points-overview">
      <el-card class="points-card">
        <div class="points-info">
          <div class="points-main">
            <div class="points-balance">
              <span class="points-number">{{ pointsInfo.available_points || 0 }}</span>
              <span class="points-unit">积分</span>
            </div>
            <div class="points-level">
              <el-tag :type="getLevelTagType(pointsInfo.level)" size="large">
                {{ pointsInfo.level_name || '青铜会员' }}
              </el-tag>
            </div>
          </div>
          
          <div class="points-stats">
            <div class="stat-item">
              <div class="stat-value">{{ pointsInfo.total_points || 0 }}</div>
              <div class="stat-label">累计获得</div>
            </div>
            <div class="stat-item">
              <div class="stat-value">{{ pointsInfo.used_points || 0 }}</div>
              <div class="stat-label">已使用</div>
            </div>
            <div class="stat-item">
              <div class="stat-value">{{ pointsInfo.level_points || 0 }}</div>
              <div class="stat-label">等级积分</div>
            </div>
          </div>
        </div>
        
        <div class="level-progress">
          <div class="progress-info">
            <span>会员等级进度</span>
            <span>{{ getNextLevelInfo() }}</span>
          </div>
          <el-progress 
            :percentage="getLevelProgress()" 
            :stroke-width="8"
            :show-text="false"
          />
        </div>
      </el-card>
    </div>

    <!-- 功能区域 -->
    <div class="points-actions">
      <el-row :gutter="20">
        <el-col :span="8">
          <el-card class="action-card" @click="handleCheckin" :class="{ disabled: checkinStatus.checked_today }">
            <div class="action-content">
              <el-icon class="action-icon" :class="{ checked: checkinStatus.checked_today }">
                <Calendar />
              </el-icon>
              <div class="action-text">
                <h3>{{ checkinStatus.checked_today ? '今日已签到' : '每日签到' }}</h3>
                <p>{{ checkinStatus.checked_today ? `连续${checkinStatus.consecutive_days}天` : '签到获得积分' }}</p>
              </div>
            </div>
          </el-card>
        </el-col>
        
        <el-col :span="8">
          <el-card class="action-card" @click="showExchangeDialog = true">
            <div class="action-content">
              <el-icon class="action-icon"><Present /></el-icon>
              <div class="action-text">
                <h3>积分兑换</h3>
                <p>积分兑换优惠券</p>
              </div>
            </div>
          </el-card>
        </el-col>
        
        <el-col :span="8">
          <el-card class="action-card" @click="activeTab = 'records'">
            <div class="action-content">
              <el-icon class="action-icon"><Document /></el-icon>
              <div class="action-text">
                <h3>积分明细</h3>
                <p>查看积分记录</p>
              </div>
            </div>
          </el-card>
        </el-col>
      </el-row>
    </div>

    <!-- 积分记录 -->
    <el-card class="records-card">
      <template #header>
        <div class="card-header">
          <span>积分记录</span>
          <el-button text @click="loadPointRecords">刷新</el-button>
        </div>
      </template>
      
      <div class="records-list">
        <div 
          v-for="record in pointRecords" 
          :key="record.id"
          class="record-item"
        >
          <div class="record-info">
            <div class="record-source">
              <el-icon>
                <component :is="getSourceIcon(record.source)" />
              </el-icon>
              <span>{{ getSourceText(record.source) }}</span>
            </div>
            <div class="record-desc">{{ record.description }}</div>
            <div class="record-time">{{ formatDateTime(record.created_at) }}</div>
          </div>
          
          <div class="record-points" :class="{ positive: record.points > 0, negative: record.points < 0 }">
            {{ record.points > 0 ? '+' : '' }}{{ record.points }}
          </div>
        </div>
      </div>
      
      <el-empty v-if="pointRecords.length === 0" description="暂无积分记录" />
      
      <div class="records-pagination" v-if="pointRecords.length > 0">
        <el-button 
          @click="loadMoreRecords" 
          :loading="loadingMore"
          :disabled="!hasMore"
        >
          {{ hasMore ? '加载更多' : '没有更多了' }}
        </el-button>
      </div>
    </el-card>

    <!-- 积分兑换对话框 -->
    <el-dialog
      v-model="showExchangeDialog"
      title="积分兑换"
      width="500px"
    >
      <div class="exchange-options">
        <div class="exchange-item" @click="handleExchange(100, '兑换优惠券')">
          <div class="exchange-info">
            <h4>5元优惠券</h4>
            <p>满30元可用</p>
          </div>
          <div class="exchange-cost">100积分</div>
        </div>
        
        <div class="exchange-item" @click="handleExchange(200, '兑换优惠券')">
          <div class="exchange-info">
            <h4>10元优惠券</h4>
            <p>满50元可用</p>
          </div>
          <div class="exchange-cost">200积分</div>
        </div>
        
        <div class="exchange-item" @click="handleExchange(500, '兑换优惠券')">
          <div class="exchange-info">
            <h4>25元优惠券</h4>
            <p>满100元可用</p>
          </div>
          <div class="exchange-cost">500积分</div>
        </div>
      </div>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import {
  Calendar,
  Present,
  Document,
  ShoppingBag,
  Star,
  Share,
  UserFilled,
  Setting
} from '@element-plus/icons-vue'
import { 
  getMyPointsApi, 
  getPointRecordsApi, 
  checkinApi, 
  getCheckinStatusApi,
  exchangePointsApi 
} from '@/utils/api'

// 响应式数据
const pointsInfo = reactive({})
const pointRecords = ref([])
const checkinStatus = reactive({
  checked_today: false,
  consecutive_days: 0
})
const showExchangeDialog = ref(false)
const loading = ref(false)
const loadingMore = ref(false)
const hasMore = ref(true)
const currentPage = ref(0)
const pageSize = 20

// 方法
const loadPointsInfo = async () => {
  try {
    const res = await getMyPointsApi()
    if (res.code === 200) {
      Object.assign(pointsInfo, res.data)
    }
  } catch (error) {
    console.error('获取积分信息失败:', error)
    ElMessage.error('获取积分信息失败')
  }
}

const loadPointRecords = async (reset = true) => {
  try {
    if (reset) {
      currentPage.value = 0
      loadingMore.value = false
    } else {
      loadingMore.value = true
    }
    
    const res = await getPointRecordsApi(pageSize, currentPage.value * pageSize)
    if (res.code === 200) {
      const newRecords = res.data || []
      
      if (reset) {
        pointRecords.value = newRecords
      } else {
        pointRecords.value.push(...newRecords)
      }
      
      hasMore.value = newRecords.length === pageSize
      currentPage.value++
    }
  } catch (error) {
    console.error('获取积分记录失败:', error)
    ElMessage.error('获取积分记录失败')
  } finally {
    loadingMore.value = false
  }
}

const loadCheckinStatus = async () => {
  try {
    const res = await getCheckinStatusApi()
    if (res.code === 200) {
      Object.assign(checkinStatus, res.data)
    }
  } catch (error) {
    console.error('获取签到状态失败:', error)
  }
}

const handleCheckin = async () => {
  if (checkinStatus.checked_today) {
    ElMessage.info('今天已经签到过了')
    return
  }
  
  try {
    const res = await checkinApi()
    if (res.code === 200) {
      ElMessage.success(`签到成功！获得${res.data.points_earned}积分`)
      await loadCheckinStatus()
      await loadPointsInfo()
      await loadPointRecords(true)
    }
  } catch (error) {
    console.error('签到失败:', error)
    ElMessage.error(error.response?.data?.message || '签到失败')
  }
}

const handleExchange = async (points, description) => {
  if (pointsInfo.available_points < points) {
    ElMessage.error('积分余额不足')
    return
  }
  
  try {
    await ElMessageBox.confirm(
      `确定要花费${points}积分进行兑换吗？`,
      '确认兑换',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      }
    )
    
    const res = await exchangePointsApi(points, 'coupon', description)
    if (res.code === 200) {
      ElMessage.success('兑换成功！')
      showExchangeDialog.value = false
      await loadPointsInfo()
      await loadPointRecords(true)
    }
  } catch (error) {
    if (error !== 'cancel') {
      console.error('积分兑换失败:', error)
      ElMessage.error(error.response?.data?.message || '积分兑换失败')
    }
  }
}

const loadMoreRecords = () => {
  loadPointRecords(false)
}

const getLevelTagType = (level) => {
  const typeMap = {
    bronze: '',
    silver: 'info',
    gold: 'warning',
    diamond: 'success'
  }
  return typeMap[level] || ''
}

const getLevelProgress = () => {
  const levelPoints = pointsInfo.level_points || 0
  const levelMap = {
    bronze: { min: 0, max: 1000 },
    silver: { min: 1000, max: 5000 },
    gold: { min: 5000, max: 10000 },
    diamond: { min: 10000, max: 10000 }
  }
  
  const currentLevel = levelMap[pointsInfo.level] || levelMap.bronze
  if (pointsInfo.level === 'diamond') return 100
  
  const progress = ((levelPoints - currentLevel.min) / (currentLevel.max - currentLevel.min)) * 100
  return Math.min(Math.max(progress, 0), 100)
}

const getNextLevelInfo = () => {
  const levelPoints = pointsInfo.level_points || 0
  const levelMap = {
    bronze: { next: 'silver', need: 1000 },
    silver: { next: 'gold', need: 5000 },
    gold: { next: 'diamond', need: 10000 },
    diamond: { next: null, need: 0 }
  }
  
  const current = levelMap[pointsInfo.level] || levelMap.bronze
  if (!current.next) return '已达最高等级'
  
  const needed = current.need - levelPoints
  return needed > 0 ? `还需${needed}积分升级` : '可升级'
}

const getSourceIcon = (source) => {
  const iconMap = {
    order: ShoppingBag,
    signin: Calendar,
    share: Share,
    review: Star,
    invite: UserFilled,
    admin: Setting,
    activity: Present
  }
  return iconMap[source] || Document
}

const getSourceText = (source) => {
  const textMap = {
    order: '订单消费',
    signin: '每日签到',
    share: '分享获得',
    review: '评价获得',
    invite: '邀请好友',
    admin: '管理员操作',
    activity: '活动获得',
    exchange: '积分兑换'
  }
  return textMap[source] || '其他'
}

const formatDateTime = (dateStr) => {
  return new Date(dateStr).toLocaleString('zh-CN')
}

// 生命周期
onMounted(() => {
  loadPointsInfo()
  loadPointRecords()
  loadCheckinStatus()
})
</script>

<style lang="less" scoped>
.points-page {
  padding: 20px;
}

.page-header {
  margin-bottom: 20px;
}

.page-title {
  margin: 0;
  color: #333;
}

.points-overview {
  margin-bottom: 20px;
}

.points-card {
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  color: white;
  border: none;

  :deep(.el-card__body) {
    padding: 30px;
  }
}

.points-info {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.points-main {
  display: flex;
  align-items: center;
  gap: 20px;
}

.points-balance {
  display: flex;
  align-items: baseline;
  gap: 5px;

  .points-number {
    font-size: 48px;
    font-weight: bold;
  }

  .points-unit {
    font-size: 16px;
    opacity: 0.8;
  }
}

.points-stats {
  display: flex;
  gap: 30px;
}

.stat-item {
  text-align: center;

  .stat-value {
    font-size: 24px;
    font-weight: bold;
    margin-bottom: 5px;
  }

  .stat-label {
    font-size: 14px;
    opacity: 0.8;
  }
}

.level-progress {
  .progress-info {
    display: flex;
    justify-content: space-between;
    margin-bottom: 10px;
    font-size: 14px;
    opacity: 0.9;
  }
}

.points-actions {
  margin-bottom: 20px;
}

.action-card {
  cursor: pointer;
  transition: all 0.3s ease;

  &:hover {
    transform: translateY(-2px);
    box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
  }

  &.disabled {
    cursor: not-allowed;
    opacity: 0.6;
  }
}

.action-content {
  display: flex;
  align-items: center;
  gap: 15px;
  padding: 10px;
}

.action-icon {
  font-size: 32px;
  color: #667eea;

  &.checked {
    color: #52c41a;
  }
}

.action-text {
  h3 {
    margin: 0 0 5px 0;
    color: #333;
    font-size: 16px;
  }

  p {
    margin: 0;
    color: #666;
    font-size: 14px;
  }
}

.records-card {
  .card-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
  }
}

.records-list {
  display: flex;
  flex-direction: column;
  gap: 15px;
}

.record-item {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 15px;
  background: #f9f9f9;
  border-radius: 8px;
}

.record-info {
  flex: 1;
}

.record-source {
  display: flex;
  align-items: center;
  gap: 8px;
  margin-bottom: 5px;

  .el-icon {
    color: #667eea;
  }

  span {
    font-weight: 500;
    color: #333;
  }
}

.record-desc {
  color: #666;
  font-size: 14px;
  margin-bottom: 5px;
}

.record-time {
  color: #999;
  font-size: 12px;
}

.record-points {
  font-size: 18px;
  font-weight: bold;

  &.positive {
    color: #52c41a;
  }

  &.negative {
    color: #ff4d4f;
  }
}

.records-pagination {
  text-align: center;
  margin-top: 20px;
}

.exchange-options {
  display: flex;
  flex-direction: column;
  gap: 15px;
}

.exchange-item {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 15px;
  border: 1px solid #e8e8e8;
  border-radius: 8px;
  cursor: pointer;
  transition: all 0.3s ease;

  &:hover {
    border-color: #667eea;
    background: #f0f2ff;
  }
}

.exchange-info {
  h4 {
    margin: 0 0 5px 0;
    color: #333;
  }

  p {
    margin: 0;
    color: #666;
    font-size: 14px;
  }
}

.exchange-cost {
  font-size: 16px;
  font-weight: bold;
  color: #667eea;
}

@media (max-width: 768px) {
  .points-info {
    flex-direction: column;
    align-items: flex-start;
    gap: 20px;
  }

  .points-stats {
    gap: 20px;
  }

  .action-content {
    flex-direction: column;
    text-align: center;
    gap: 10px;
  }

  .record-item {
    flex-direction: column;
    align-items: flex-start;
    gap: 10px;
  }
}
</style>
